<template>
  <div class="login-container">
    <div class="login-form-wrapper">
      <div class="login-header">
        <h2>欢迎登录</h2>
        <p>请输入您的账号信息</p>
      </div>

      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form" label-position="left"
        label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" prefix-icon="User" clearable
            :style="inputStyle" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock" show-password
            clearable :style="inputStyle" />
        </el-form-item>
        <el-form-item v-if="!isLogin" label="确认密码" prop="passwordConfirm">
          <el-input v-model="loginForm.passwordConfirm" type="password" placeholder="请确认密码" prefix-icon="Lock"
            show-password clearable :style="inputStyle" />
        </el-form-item>

        <el-form-item label="验证码" prop="checkCode">
          <el-row :gutter="10">
            <el-col :span="15">
              <el-input v-model="loginForm.checkCode" placeholder="请输入验证码" prefix-icon="Check" clearable
                :style="inputStyle" />
            </el-col>
            <el-col :span="9">
              <el-image :src="checkCodeImgSrc" alt="验证码" style="height: 40px; cursor: pointer;"
                @click="changeCheckCode" />
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <el-form>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleLogin" :disabled="loading" class="login-button"
            :style="buttonStyle">
            <template v-if="loading">
              <!-- <el-icon>
                <Loading />
              </el-icon> -->
              <span>登录中...</span>
            </template>
            <template v-else>
              {{ isLogin ? '登录' : '注册' }}
            </template>
          </el-button>
        </el-form-item>
        <el-form-item style="width: 100%;">
          <!-- <el-checkbox v-model="loginForm.remember">记住密码</el-checkbox> -->
          <el-link type="primary" :underline="false" class="forgot-password">忘记密码？</el-link>
        </el-form-item>

        <div class="login-footer">
          <el-link type="primary" :underline="false" @click="changeoptype">{{ isLogin ? '注册账号' : '返回登录' }}</el-link>
        </div>
      </el-form>
    </div>
  </div>


</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock, Loading } from '@element-plus/icons-vue'
import axios from 'axios'
import router from '../router'
import api from '../utils/api'
// 表单引用
const loginFormRef = ref(null)

// 加载状态
const loading = ref(false)
//登录注册跳转判断
const isLogin = ref(true);
// 验证码图片源
const checkCodeImgSrc = ref('')

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  passwordConfirm: '',
  checkCode: '',
  remember: false
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在 3 到 20 个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 30, message: '密码长度应在 6 到 30 个字符之间', trigger: 'blur' }
  ]
  ,
  passwordConfirm: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== loginForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  checkCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
  ]
}

// 函数  

// 切换登录注册
const changeoptype = () => {
  isLogin.value = !isLogin.value;
  loginForm.username = '';
  loginForm.password = '';
  loginForm.passwordConfirm = '';
  loginForm.checkCode = '';
  changeCheckCode();
}

// 获取验证码
const changeCheckCode = async () => {
  // const res = await fetch('')
  // const data = await res.json()
  // console.log(api.checkcode);
  axios.get(api.checkcode)
    .then(function (response) {
      // 成功处理
      // console.log(response.data.data.checkCode);
      checkCodeImgSrc.value = response.data.data.checkCode;
      //   // 浏览器本地存储
      localStorage.setItem("checkCodeKey", response.data.data.key);
      // console.log("存入key是：", localStorage.getItem("checkCodeKey"));
    })
    .catch(function (error) {
      // 错误处理
      console.log("错误" + error);
    })
    .finally(function () {
      // 总是执行
    });
}



// 处理登录
const handleLogin = async () => {

  let headers = {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'X-Requested-With': 'XMLHttpRequest',
  } 

  try {
    // 表单验证
    await loginFormRef.value.validate()


    // 构建表单数据
    const formData = new URLSearchParams();
    formData.append('checkCodeKey', localStorage.getItem("checkCodeKey"));
    formData.append('username', loginForm.username);
    formData.append('password', loginForm.password);
    formData.append('checkCode', loginForm.checkCode);
    axios.post(isLogin ? api.login : api.register, formData, {
      headers: headers
    })
      .then(function (response) {
        console.log(response.data);
        loading.value = true
        if (response.data.code == 200) {
          
          setTimeout(() => {
            // 设置加载状态
            loading.value = false
            ElMessage.success('登录成功')
            // 
            localStorage.setItem("token", response.data.data.token);
            console.log(response.data.data.token);
            
            // 跳转到聊天主界面
            router.push('/MusicHome')
          }, 500)
        } else {
          changeCheckCode()
          ElMessage.error(response.data.data)
        }
      })
      .catch(function (error) {
        console.log(error);
      });
  } catch (error) {
    console.log('表单验证失败:', error)
  } finally {
    loading.value = false // 确保在完成所有操作后重置加载状态
  }

}


changeCheckCode()

// 样式计算属性 - 便于统一样式管理
const inputStyle = computed(() => ({
  borderColor: '#dcdfe6',
  '&:hover': {
    borderColor: '#c0c4cc'
  },
  '&.is-focus': {
    borderColor: '#8294c4',
    boxShadow: '0 0 0 2px rgba(130, 148, 196, 0.2)'
  }
}))

const buttonStyle = computed(() => ({
  backgroundColor: '#8294c4',
  borderColor: '#8294c4',
  '&:hover': {
    backgroundColor: '#6b82b6',
    borderColor: '#6b82b6'
  },
  '&:active': {
    backgroundColor: '#5e73a3',
    borderColor: '#5e73a3'
  }
}))
</script>

<style scoped>
/* 登录容器 */
.login-container {
  display: flex;
  width: 100%;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
}

/* 登录表单包装器 */
.login-form-wrapper {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 40px;
  animation: fadeIn 0.5s ease-in-out;
}

/* 登录头部 */
.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #495057;
  font-size: 22px;
  font-weight: 500;
  margin-bottom: 8px;
}

.login-header p {
  color: #adb5bd;
  font-size: 14px;
}

/* 登录表单 */
.login-form {
  width: 100%;
}

/* 表单标签 */
.el-form-item__label {
  color: #6c757d;
  font-size: 14px;
  font-weight: normal;
}

/* 忘记密码链接 */
.forgot-password {
  float: right;
  font-size: 13px;
  color: #8294c4;
}

.forgot-password:hover {
  color: #6b82b6;
}

/* 登录按钮 */
.login-button {
  width: 100%;
  height: 40px;
  font-size: 15px;
  letter-spacing: normal;

  border-radius: 4px;
}

/* 登录页脚 */
.login-footer {
  text-align: center;
  margin-top: 20px;
}

.login-footer .el-link {
  color: #8294c4;
  font-size: 14px;
}

.login-footer .el-link:hover {
  color: #6b82b6;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 复选框样式 */
.el-checkbox__label {
  color: #6c757d;
  font-size: 13px;
}

/* 输入框图标颜色 */
:deep(.el-input__prefix-icon) {
  color: #adb5bd;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .login-form-wrapper {
    padding: 30px 20px;
  }

  .login-header h2 {
    font-size: 20px;
  }
}
</style>